package thread;

import java.util.PriorityQueue;

class MyTimertask1 implements Comparable<MyTimertask1>{
    private long time;
    private Runnable runnable;

    public MyTimertask1(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }

    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTimertask1 o) {
        return (int) (this.time-o.time);
    }


    public void run() {
        runnable.run();
    }
}


class MyTimerr{
    private Thread t=null;
    private PriorityQueue<MyTimertask1> queue=new PriorityQueue<>();
    private Object locker =new Object();

    public void schedule(Runnable runnable,long delay){
        MyTimertask1 task=new MyTimertask1(runnable,delay);
        queue.offer(task);
        locker.notify();
    }

    public MyTimerr(){
        t=new Thread(()->{
            while (true){
                synchronized (locker){
                  try {
                      if (queue.isEmpty()){
                          locker.wait();
                      }
                      MyTimertask1 task=queue.peek();
                      long curTime=System.currentTimeMillis();
                      if (curTime>=task.getTime()){
                          queue.poll();
                          task.run();
                      }else {
                         locker.wait();
                      }
                  }catch (InterruptedException e){
                      e.printStackTrace();
                  }
                }
            }
        });
    }

}



public class ThreadDemo30 {
}
